package filter;

import service.impl.UserServiceImpl;
import ssm.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
@WebFilter(urlPatterns = "/jsp/login.jsp",dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD})
public class AutoUserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        Cookie[] cookies = request.getCookies();
        //判断cookies是否为空
        if (cookies != null) {

            for (Cookie c : cookies) {
                //判断所有Cookie里是否有autouser
                if (c.getName().equals("autouser")) {
                    //判断autouser的值是否为null
                    if (c.getValue() != null) {
                        String value = c.getValue();
                        String decode = URLDecoder.decode(value, "utf-8");
                        String[] split = decode.split(":");
                        String username = split[0];
                        String password = split[1];
                        UserServiceImpl userService = new UserServiceImpl();
                        User user = userService.foundUByNP(username,password);
                        if (user != null) {
                            request.getSession().setAttribute("user", user);
                            response.sendRedirect(request.getContextPath()+"/");

                        } else {
                            chain.doFilter(req, resp);
                        }
                    } else {
                        chain.doFilter(req, resp);
                    }
                } else {
                    chain.doFilter(req, resp);
                }
            }
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {

    }
}
